package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.DeleteFavorReq;
import com.ydkj.a37e_mall.Classes.Model.Request.MyFavorReq;
import com.ydkj.a37e_mall.Classes.Model.Response.MyFavorResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;


/**
 * Created by Administrator on 2017/1/18.
 * 我的收藏
 */

public class MyCollectionActivity extends BaseActivity implements View.OnClickListener {
    Activity mActivity;
    private ImageView img_back;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private PullToRefreshListView lv_my_collect;
    private CollectAdapter collectAdapter;
    private TextView tv_edit, tv_cancel_collect, tv_no_collect_data;
    private String secret;
    private boolean is_edit = false;
    private List<MyFavorResp.ResultEntity.DataEntity> favorlist;
    private List<String> delete_idList;//保存选择删除收藏商品id

    public static final int LOAD = 0;// 加载
    public static final int REFRESH = 1;// 刷新
    public static final int MORE = 2;// 更多

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_collection);
        mActivity = this;
        init();
        GetMyFavor(REFRESH);
//        initWindow();
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.A000000), 0);

    }

    private void init() {
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();
        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_edit = (TextView) mActivity.findViewById(R.id.tv_edit);
        tv_cancel_collect = (TextView) mActivity.findViewById(R.id.tv_cancel_collect);
        tv_no_collect_data = (TextView) mActivity.findViewById(R.id.tv_no_collect_data);


        favorlist = new ArrayList<>();
        delete_idList = new ArrayList<>();
        lv_my_collect = (PullToRefreshListView) mActivity.findViewById(R.id.lv_my_collect);
        collectAdapter = new CollectAdapter(favorlist);
        lv_my_collect.setAdapter(collectAdapter);
        lv_my_collect.setOnRefreshListener2(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                GetMyFavor(REFRESH);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                GetMyFavor(MORE);

            }
        });

        tv_edit.setOnClickListener(this);
        tv_cancel_collect.setOnClickListener(this);
    }

    //获取收藏列表
    private void GetMyFavor(final int type) {
        CustomProgressDialog.createDialog(mActivity).show();
        MyFavorReq req = new MyFavorReq();
        if (type == LOAD || type == REFRESH) {
            page = 1;
        } else {
            page = favorlist.size() / 20 + 1;
        }
        req.setUuid(myApplication.getDataEntity().getUuid());
        req.setPage(page + "");
        req.setPage_size(10 + "");

        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                lv_my_collect.onRefreshComplete();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                Log.e("ssss", "GetMyFavor==response==>" + response);

                if (errmsg.equals("暂无收藏")) {
                    favorlist.clear();
                    collectAdapter.notifyDataSetChanged();
                    lv_my_collect.onRefreshComplete();
                    return;
                }
                if (errno.equals("000")) {
                    MyFavorResp resp = GsonImpl.get().toObject(response.toString(), MyFavorResp.class);
                    if (type == LOAD || type == REFRESH) {
                        favorlist.clear();
                        favorlist.addAll(resp.getResult().getData());
                    } else {
                        favorlist.addAll(resp.getResult().getData());
                    }
                    if (favorlist.size() % 10 > 0) {
                        lv_my_collect.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    } else {
                        lv_my_collect.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                    collectAdapter.notifyDataSetChanged();
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                lv_my_collect.onRefreshComplete();
                CommonUtil.showToast(mActivity, "网络连接失败");
                CustomProgressDialog.Dismiss();
            }
        });
    }

    //删除收藏商品
    private void DeleteFavor() {
        CustomProgressDialog.createDialog(mActivity).show();
        DeleteFavorReq req = new DeleteFavorReq();
        delete_idList.clear();
        for (MyFavorResp.ResultEntity.DataEntity dataEntity : favorlist) {
            if (dataEntity.getProduct().is_delete() == true) {
                delete_idList.add(dataEntity.getId());
            }
        }

        if (delete_idList.size() == 0) {
            CustomProgressDialog.Dismiss();
            delete_idList.clear();
            CommonUtil.showToast(mActivity, "请至少选择一条记录");
            return;
        }

        Log.e("ssss", "id==>" + CommonUtil.listToString(delete_idList, ','));

        req.setId(CommonUtil.listToString(delete_idList, ','));

        RequestParams params = new RequestParams();
        params.put("uuid", myApplication.getDataEntity().getUuid());
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Log.e("ssss", "id==>" + CommonUtil.listToString(delete_idList, ';'));
        Log.e("ssss", "uuid==>" + myApplication.getDataEntity().getUuid());
        Log.e("ssss", "token==>" + sharedPreferencesUtil.getAccessToken());
        Log.e("ssss", "secret==>" + req.getSecret());

        AsyncHttpClient client = new AsyncHttpClient();
        client.put(Const.COMMON_ADDRESS + req.urlString() + myApplication.getDataEntity().getUuid(), params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        CustomProgressDialog.Dismiss();
                        String errno = response.optString("errno");
                        String errmsg = response.optString("errmsg");
                        Log.e("ssss", "DeleteFavor==response==>" + response);
                        if (errno.equals("000")) {
                            CommonUtil.showToast(mActivity, errmsg);
                            GetMyFavor(REFRESH);
                            is_edit=false;
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        super.onFailure(statusCode, headers, responseString, throwable);
                        CustomProgressDialog.Dismiss();
                        CommonUtil.showToast(mActivity, Networkfailure);

                    }
                }

        );
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_edit://编辑
                if (is_edit == false) {
                    tv_edit.setText("完成");
                    tv_cancel_collect.setVisibility(View.VISIBLE);
                    is_edit = true;
                } else {
                    tv_edit.setText("编辑");
                    tv_cancel_collect.setVisibility(View.GONE);
                    is_edit = false;
                }
//                collectAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_cancel_collect://取消收藏
                delete_idList.clear();
//                for (MyFavorResp.ResultEntity.DataEntity dataEntity : favorlist) {
//                    if (dataEntity.getProduct().is_delete() == true) {
//
//                        delete_idList.add(dataEntity.getId());
//                    }
//                }
//                Log.e("ssss", "delete_idList==>" + delete_idList.size());
//
//                Log.e("ssss", "id==>" + CommonUtil.listToString(delete_idList, ';'));

                DeleteFavor();

                break;
        }
    }

    //收藏列表
    private class CollectAdapter extends BaseAdapter {
        private List<MyFavorResp.ResultEntity.DataEntity> myCollectInfoList;

        private CollectAdapter(List<MyFavorResp.ResultEntity.DataEntity> infos) {
            if (infos == null) {
                infos = new ArrayList<MyFavorResp.ResultEntity.DataEntity>();
            }
            myCollectInfoList = infos;
        }

        @Override
        public int getCount() {
            return myCollectInfoList.size();
        }

        /**
         * 获得某一位置的数据
         */
        @Override
        public MyFavorResp.ResultEntity.DataEntity getItem(int position) {
            return myCollectInfoList.get(position);
        }


        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.my_collect_listitem, null);
                vh = new ViewHolder();
//                vh.img_choose = (ImageView) convertView.findViewById(R.id.img_choose);
                vh.cb_choose = (CheckBox) convertView.findViewById(R.id.cb_choose);
                vh.img_thumb = (ImageView) convertView.findViewById(R.id.img_thumb);
                vh.tv_product_name = (TextView) convertView.findViewById(R.id.tv_product_name);
                vh.tv_describe = (TextView) convertView.findViewById(R.id.tv_describe);
                vh.tv_price = (TextView) convertView.findViewById(R.id.tv_price);
                vh.tv_buy_number = (TextView) convertView.findViewById(R.id.tv_buy_number);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            convertView.setClickable(true);

            ImageLoader.getInstance().displayImage(getItem(position).getThumb(), vh.img_thumb);
            vh.tv_product_name.setText(getItem(position).getName());
//            vh.tv_describe.setText(getItem(position).getProduct().getDescription());
            vh.tv_price.setText(getItem(position).getPrice());
//            vh.tv_buy_number.setText(getItem(position).getProduct().getSales() + "人付款");


            if (is_edit == true) {
                vh.cb_choose.setVisibility(View.VISIBLE);
                tv_edit.setText("完成");
                tv_cancel_collect.setVisibility(View.VISIBLE);

            } else {
                vh.cb_choose.setVisibility(View.GONE);
                tv_edit.setText("编辑");
                tv_cancel_collect.setVisibility(View.GONE);
            }

            vh.cb_choose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        getItem(position).getProduct().setIs_delete(true);
                    }
                    if (!isChecked) {
                        getItem(position).getProduct().setIs_delete(false);
                    }
                    collectAdapter.notifyDataSetChanged();
                }
            });
//
            if (getItem(position).getProduct().is_delete() == false) {
                vh.cb_choose.setChecked(false);
            } else if (getItem(position).getProduct().is_delete() == true) {
                vh.cb_choose.setChecked(true);
            }
//
            final ViewHolder finalVh = vh;
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (is_edit == true) {
                        if (getItem(position).getProduct().is_delete() == false) {
                            finalVh.cb_choose.setChecked(true);
                            getItem(position).getProduct().setIs_delete(true);

                        } else {
                            finalVh.cb_choose.setChecked(false);
                            getItem(position).getProduct().setIs_delete(false);
                        }
                        collectAdapter.notifyDataSetChanged();
                    } else {
                        Intent intent = new Intent(mActivity, ProductDetails.class);
                        intent.putExtra("id", getItem(position).getProduct_id());
//                        intent.putExtra("is_Integral", getItem(position).getIs_integral());
                        startActivity(intent);
                    }
                }
            });

            return convertView;
        }

        private class ViewHolder {
            private ImageView img_choose, img_thumb;
            public TextView tv_product_name, tv_describe, tv_price, tv_buy_number;
            private CheckBox cb_choose;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == Activity.RESULT_OK) {
//                    LoadCollectProduct(REFRESH);
                }
                break;
        }
    }
}
